<script setup lang="ts">
import {computed, ref, onMounted, onUnmounted} from "vue";
import CodeEditor from "../../../components/code/CodeEditor.vue";
import {CircleCloseFilled} from "@element-plus/icons-vue";
import {QuestionType} from "../../question/addQuestion/types/questionTypes";
import {ChoiceOptionVO, TestCaseVO} from "../../../../generated";

interface SubmitResult {
  questionName?: string;
  username?: string;
  submitTime?: string;
  judgeTime?: string;
  compiler?: string;
  memory?: string;
  time?: string;
  status?: number;
  score?: string;
  testCaseList?: TestCaseVO[];
  code?: string;
  compilerOutput?: string;
  errorMessage?: string;
  showWaitingInfo?: boolean;
  waitingInfo?: string;
  questionType?: QuestionType;
  userInput?: string;
  choiceOptionList?: ChoiceOptionVO[];
  judgement?: number;
  fillBlanks?: string[];
  comprehensive?: string;
  analysis?: string;
  suggestion?: string;
  referenceAnswer?: string;
}

const props = defineProps<{
  visible: boolean
  result?: SubmitResult
}>()

const emit = defineEmits(['update:visible'])

const dialogTableVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const handleCodeEditorChange = () => {
  console.log("this editor is read only")
}

const handleClose = () => {
  dialogTableVisible.value = false
}

// 修改状态码映射中的类型
const statusMap: Record<number, { text: string; type: string }> = {
  0: {text: '等待评测', type: 'waiting'},
  1: {text: '正在评测', type: 'running'},
  2: {text: '编译错误', type: 'compile-error'},
  3: {text: '答案正确', type: 'accepted'},
  4: {text: '部分正确', type: 'other'},
  5: {text: '格式错误', type: 'other'},
  6: {text: '答案错误', type: 'other'},
  7: {text: '多种错误', type: 'other'},
  8: {text: '运行超时', type: 'other'},
  9: {text: '内存超限', type: 'other'},
  10: {text: '非零返回', type: 'other'},
  11: {text: '段错误', type: 'other'},
  12: {text: '浮点错误', type: 'other'},
  13: {text: '输出超限', type: 'other'},
  14: {text: '内部错误', type: 'internal-error'},
  15: {text: '运行时错误', type: 'other'}
}

// 添加获取状态信息的计算属性
const statusInfo = computed(() => {
  const status = Number(props.result?.status)
  return statusMap[status] || {text: '未知状态', type: 'info'}
})

// 判断是否为编程题
const isProgrammingQuestion = computed(() => {
  return props.result?.questionType === QuestionType.PROGRAMMING;
})

// 判断是否为选择题
const isMultipleChoiceQuestion = computed(() => {
  return props.result?.questionType === QuestionType.MULTIPLE_CHOICE;
})

// 判断是否为判断题
const isJudgementQuestion = computed(() => {
  return props.result?.questionType === QuestionType.JUDGEMENT;
})

// 判断是否为填空题
const isFillBlankQuestion = computed(() => {
  return props.result?.questionType === QuestionType.FILL_BLANK;
})

// 判断是否为综合题
const isComprehensiveQuestion = computed(() => {
  return props.result?.questionType === QuestionType.COMPREHENSIVE;
})

// 解析用户输入
const parsedUserInput = computed(() => {
  if (!props.result?.userInput) return null;

  try {
    const parsed = JSON.parse(props.result.userInput);

    // 如果是选择题或填空题，以数组形式解析，并使用、分割
    if (isMultipleChoiceQuestion.value || isFillBlankQuestion.value) {
      if (Array.isArray(parsed)) {
        return parsed.join('、');
      }
    }

    return parsed;
  } catch (e) {
    return props.result.userInput;
  }
})

// 添加响应式检测
const isMobile = ref(false);

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
};

onMounted(() => {
  checkMobile();
  window.addEventListener('resize', checkMobile);
});

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);
});
</script>

<template>
  <el-dialog
      v-model="dialogTableVisible"
      :show-close="false"
      :width="isMobile ? '95%' : '900'"
      :top="isMobile ? '2vh' : '5vh'"
      :fullscreen="isMobile"
  >
    <template #header>
      <div class="my-header">
        <span class="submission-title">提交结果</span>
        <el-button type="danger" @click="handleClose">
          <el-icon class="el-icon--left">
            <CircleCloseFilled/>
          </el-icon>
          关闭
        </el-button>
      </div>
    </template>
    <el-alert v-if="props.result?.showWaitingInfo" style="margin-bottom: 15px" :title="props.result?.waitingInfo"
              type="info" show-icon/>
    <div class="result-info">
      <div class="info-row">
        <div class="info-item">
          <span class="label">题目</span>
          <span class="value">{{ props.result?.questionName }}</span>
        </div>
        <div class="info-item">
          <span class="label">用户</span>
          <span class="value">{{ props.result?.username }}</span>
        </div>
        <div class="info-item">
          <span class="label">提交时间</span>
          <span class="value">{{ props.result?.submitTime }}</span>
        </div>
      </div>

      <div class="info-row">
        <!-- 只有编程题才显示编译器、内存、时间信息 -->
        <template v-if="isProgrammingQuestion">
          <div class="info-item">
            <span class="label">编译器</span>
            <span class="value">{{ props.result?.compiler }}</span>
          </div>
          <div class="info-item">
            <span class="label">内存</span>
            <span class="value">{{ props.result?.memory }}</span>
          </div>
          <div class="info-item">
            <span class="label">用时</span>
            <span class="value">{{ props.result?.time }}</span>
          </div>
        </template>
        <template v-else>
          <div class="info-item">
            <span class="label">题型</span>
            <span class="value">
              {{
                isMultipleChoiceQuestion ? '选择题' :
                    isJudgementQuestion ? '判断题' :
                        isFillBlankQuestion ? '填空题' :
                            isComprehensiveQuestion ? '综合题' : '未知题型'
              }}
            </span>
          </div>
          <div class="info-item"></div>
          <div class="info-item"></div>
        </template>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">状态</span>
          <span :class="['value', `status-${statusInfo.type}`]">
            {{ statusInfo.text }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">分数</span>
          <span class="value">{{ props.result?.score }}</span>
        </div>
        <div class="info-item">
          <span class="label">评测时间</span>
          <span class="value">{{ props.result?.judgeTime }}</span>
        </div>
      </div>
    </div>

    <!-- 用户输入显示区域 -->
    <div class="card" v-if="!isProgrammingQuestion && parsedUserInput">
      <div class="card-header">
        <span>用户答案</span>
      </div>
      <div class="card-body">
        <div v-if="isMultipleChoiceQuestion">
          <p>{{ parsedUserInput }}</p>
        </div>
        <div v-else-if="isJudgementQuestion">
          <p>{{ parsedUserInput === 1 ? '正确' : '错误' }}</p>
        </div>
        <div v-else-if="isFillBlankQuestion">
          <p>{{ parsedUserInput }}</p>
        </div>
        <div v-else-if="isComprehensiveQuestion">
          <p>{{ parsedUserInput }}</p>
        </div>
      </div>
    </div>

    <!-- 参考答案区域 -->
    <div class="card" v-if="!isProgrammingQuestion">
      <div class="card-header">
        <span>参考答案</span>
      </div>
      <div class="card-body">
        <!-- 选择题答案 -->
        <div v-if="isMultipleChoiceQuestion && props.result?.choiceOptionList">
          <el-table :data="props.result.choiceOptionList" style="width: 100%">
            <el-table-column prop="option" label="选项"></el-table-column>
            <el-table-column label="是否正确" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isCorrect ? 'success' : 'info'">
                  {{ scope.row.isCorrect ? '正确' : '错误' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="analysis" label="解析"
                             v-if="props.result.choiceOptionList.some(item => item.analysis)"></el-table-column>
          </el-table>
        </div>

        <!-- 判断题答案 -->
        <div v-else-if="isJudgementQuestion && props.result?.judgement !== undefined">
          <p>{{ props.result.judgement === 1 ? '正确' : '错误' }}</p>
          <div v-if="props.result.analysis" class="answer-analysis">
            <div class="analysis-title">解析：</div>
            <div class="analysis-content">{{ props.result.analysis }}</div>
          </div>
        </div>

        <!-- 填空题答案 -->
        <div v-else-if="isFillBlankQuestion && props.result?.fillBlanks">
          <div v-for="(blank, index) in props.result.fillBlanks" :key="index" class="fill-blank-item">
            <div class="blank-index">空格{{ index + 1 }}：</div>
            <div class="blank-answer">{{ blank }}</div>
          </div>
          <div v-if="props.result.analysis" class="answer-analysis">
            <div class="analysis-title">解析：</div>
            <div class="analysis-content">{{ props.result.analysis }}</div>
          </div>
        </div>

        <!-- 综合题答案 -->
        <div v-else-if="isComprehensiveQuestion && props.result?.comprehensive">
          <div>{{ props.result.comprehensive }}</div>
          <div v-if="props.result.referenceAnswer" class="answer-analysis">
            <div class="analysis-title">参考答案：</div>
            <div class="analysis-content">{{ props.result.referenceAnswer }}</div>
          </div>
          <div v-if="props.result.suggestion" class="answer-analysis">
            <div class="analysis-title">修改建议：</div>
            <div class="analysis-content">{{ props.result.suggestion }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 以下内容仅在编程题时显示 -->
    <template v-if="isProgrammingQuestion">
      <div class="card" v-if="props.result?.status!==2">
        <div class="card-header">
          <span>评测详情</span>
        </div>
        <div class="card-body">
          <el-table :data="props.result?.testCaseList" style="width: 100%">
            <el-table-column label="测试点" width="100">
              <template #default="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column prop="hint" label="提示"/>
            <el-table-column prop="memory" label="内存(KB)" width="120"/>
            <el-table-column prop="time" label="用时(ms)" width="120"/>
            <el-table-column prop="result" label="结果">
              <template #default="scope">
                <span :class="`status-${statusMap[scope.row.status]?.type || 'info'}`">
                  {{ statusMap[scope.row.status]?.text || '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="得分" width="100"/>
          </el-table>
        </div>
      </div>

      <div class="card">
        <div class="card-header">
          <span>提交代码</span>
        </div>
        <div class="card-body code-container">
          <code-editor
              :value="props.result?.code || ''"
              language="java"
              :handle-change="handleCodeEditorChange"
              :readonly="true"
          />
        </div>
      </div>

      <div class="card">
        <div class="card-header">
          <span>编译器输出</span>
        </div>
        <div class="card-body compiler-output">
          <pre><code>{{ props.result?.compilerOutput }}</code></pre>
        </div>
      </div>

      <div class="card" v-if="props.result?.errorMessage">
        <div class="card-header">
          <span>错误信息</span>
        </div>
        <div class="card-body compiler-output">
          <pre><code>{{ props.result?.errorMessage }}</code></pre>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
  border-bottom: 2px solid #1c80f2;
  padding-bottom: 10px;
  margin-right: 0;
}

.submission-title {
  padding: 8px 8px 8px 0;
  font-size: 18px;
  color: #1c80f2;
  font-weight: bold;
}

.result-info {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  margin-right: 10px;
  min-width: 60px;
}

.value {
  color: #303133;
}

.status-error,
.status-success,
.status-warning,
.status-info {
  display: none;
}

.status-waiting {
  color: #404040;
}

.status-running {
  color: #ffa500;
}

.status-compile-error {
  color: #0000ff;
}

.status-accepted {
  color: #ff0000;
}

.status-internal-error {
  color: #404040;
}

.status-other {
  color: #008000;
}

.section-title {
  display: none;
}

.card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
}

.card-header {
  background-color: #F6F7F9;
  padding: 12px 20px;
  font-weight: bold;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
}

.card-body {
  padding: 20px;
}

.compiler-output {
  background-color: #2d2d2d;
  color: #ffffff;
  padding: 15px;
  border-radius: 0;
  font-family: monospace;
}

.code-container {
  height: auto;
  max-height: 400px;
  overflow: auto;
}

.code-container :deep(.monaco-editor) {
  min-height: 100px;
  max-height: 300px;
}

/* 添加填空题样式 */
.fill-blank-item {
  display: flex;
  margin-bottom: 12px;
}

.blank-index {
  font-weight: bold;
  margin-right: 8px;
}

.blank-answer {
  color: #303133;
}

/* 添加解析样式 */
.answer-analysis {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #dcdfe6;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.analysis-content {
  color: #606266;
  line-height: 1.6;
}

/* 添加移动端响应式样式 */
@media screen and (max-width: 768px) {
  .my-header {
    padding: 12px 16px;
    margin: -20px -20px 20px;
  }

  .submission-title {
    font-size: 16px;
  }

  .result-info {
    padding: 12px;
    margin-bottom: 16px;
  }

  .info-row {
    flex-direction: column;
    gap: 12px;
    margin-bottom: 0;
  }

  .info-item {
    justify-content: space-between;
  }

  .label {
    min-width: auto;
  }

  .card {
    margin-bottom: 16px;
    border-radius: 4px;
  }

  .card-header {
    padding: 8px 12px;
  }

  .card-body {
    padding: 12px;
  }

  /* 调整表格在移动端的显示 */
  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table .cell) {
    padding: 8px;
  }

  /* 代码编辑器高度调整 */
  .code-container {
    max-height: 300px;
  }

  .code-container :deep(.monaco-editor) {
    min-height: 80px;
    max-height: 200px;
  }

  /* 编译器输出和错误信息区域调整 */
  .compiler-output {
    padding: 12px;
    font-size: 12px;
    max-height: 200px;
    overflow-y: auto;
  }

  /* 关闭按钮样式调整 */
  :deep(.el-button) {
    padding: 6px 12px;
    font-size: 12px;
  }

  :deep(.el-icon) {
    font-size: 14px;
  }
}
</style>